﻿using System;
using System.Data;
using NHibernate.SqlTypes;
using NHibernate.UserTypes;

namespace TestBat.Models.UserTypes
{
    public class UIntUserType : IUserType
    {
        public object Assemble(object cached, object owner)
        {
            return DeepCopy(cached);
        }

        public object DeepCopy(object value)
        {
            return value;
        }

        public object Disassemble(object value)
        {
            return DeepCopy(value);
        }

        public new bool Equals(object x, object y)
        {
            if (ReferenceEquals(x, y))
            {
                return true;
            }

            if (x == null || y == null)
            {
                return false;
            }

            return (uint)x == (uint)y;
        }

        public int GetHashCode(object x)
        {
            return x.GetHashCode();
        }

        public bool IsMutable
        {
            get { return true; }
        }

        public object NullSafeGet(System.Data.IDataReader rs, string[] names, object owner)
        {
            object value = rs.GetValue(rs.GetOrdinal(names[0]));

            if (value == null)
                return 0;

            return Convert.ToUInt32(value);
        }

        public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index)
        {
            if (value == null)
                ((IDataParameter)cmd.Parameters[index]).Value = DBNull.Value;
            else
                ((IDataParameter)cmd.Parameters[index]).Value = Convert.ToInt32(value);
        }

        public object Replace(object original, object target, object owner)
        {
            return target;
        }

        public System.Type ReturnedType
        {
            get { return typeof(uint); }
        }

        public SqlType[] SqlTypes
        {
            get { return new SqlType[] { SqlTypeFactory.Int32 }; }
        }
    }
}
